package com.ly.heart.service.king.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.spring.SpringUtils;
import com.ly.heart.domain.*;
import com.ly.heart.domain.king.BaseChildBo;
import com.ly.heart.domain.king.base.supplier.*;
import com.ly.heart.domain.king.order.FBillTypeIDBo;
import com.ly.heart.domain.king.order.FConfirmerIdBo;
import com.ly.heart.domain.king.order.OrderAuditBo;
import com.ly.heart.domain.king.order.OrderSubmitBo;
import com.ly.heart.domain.request.KingBaseSingleRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.domain.response.KingBaseResponseSuccessEntity;
import com.ly.heart.service.IKingBaseContactsService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.service.ISupplierContactsService;
import com.ly.heart.service.ISupplierService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 供应商推送Service
 */
@Component
@Slf4j
public class SupplierPushService {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd" );

    @Resource
    private ISupplierService supplierService;
    @Resource
    private IKingOrgService iKingOrgService;

    /**
     * 公用金蝶推送方法
     * 合并保存，提交，审核三步
     * @param kingInventoryId
     */
    @Transactional( rollbackFor = Exception.class )
    public void push(String supplierId){
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity>().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity::getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        SupplierEntity supplierEntity = supplierService.selectSupplierEntityById(supplierId);
        if(Objects.isNull(supplierEntity)){
            throw new CustomException("供应商不存在！");
        }
        if(supplierEntity.getIsSend() == KingConstUtil.KING_DATA_IS_SEND_YES){
            throw new CustomException("该供应商已推送金蝶,无需重复推送！");
        }
        try {
            K3CloudApi client = new K3CloudApi (identifyInfo);
            save(supplierEntity,client);
            submit(supplierEntity.getSupplierCode(),client);
            audit(supplierEntity.getSupplierCode(),client);
            updateSendSuccess(supplierEntity.getId());
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("推送供应商失败！");
        }
    }
    /**
     * 修改推送状态
     * @param kingInventoryId
     * @return
     */
    private void updateSendSuccess(String supplierId){
        SupplierEntity supplierEntity = new SupplierEntity();
        supplierEntity.setId(supplierId);
        supplierEntity.setIsSend(KingConstUtil.KING_DATA_IS_SEND_YES);
        supplierEntity.setChangeTime(DateUtils.getNowDate());
        supplierEntity.setChangeId(SecurityUtils.getLoginUser().getUser().getUserId());
        boolean flag = supplierService.updateById(supplierEntity);
        if(!flag){
            throw new CustomException("修改推送状态失败！");
        }
    }

    /**
     * 金蝶-供应商保存
     * @param supplier
     * @param client
     */
    @Transactional( rollbackFor = Exception.class )
    public void save(SupplierEntity supplier,K3CloudApi client){
        try{
            String formId = KingConstUtil.BD_Supplier;
            KingBaseSingleRequest singleRequest = new KingBaseSingleRequest ();
            SupplierBo supplierBo = this.assembleSupplier(supplier);
            System.out.println("supplierBo:"+supplierBo);
            singleRequest.setModel(supplierBo);
            //调用接口
            String resultJson = client.save(formId, JSONObject.toJSONString(singleRequest));
            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("供应商推送成功: {}", gson.toJson(repoRet.getResult()));
                List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
                if(!CollectionUtils.isEmpty(successEntities)){
                    String docCode = successEntities.get(0).getNumber();
                    //修改为已推送状态
                    supplierService.update(new LambdaUpdateWrapper<SupplierEntity>().set(SupplierEntity::getIsSend,KingConstUtil.KING_DATA_IS_SEND_YES).eq(SupplierEntity::getSupplierCode,docCode));
                }
            } else {
                log.error("供应商推送失败: " + gson.toJson(repoRet.getResult().getResponseStatus()));
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 金蝶-供应商提交
     * @param docCode
     * @param client
     */
    public void submit(String docCode, K3CloudApi client){
        try{
            OrderSubmitBo submitBo = new OrderSubmitBo();
            List<String> numbers = new ArrayList<>();
            numbers.add(docCode);
            submitBo.setNumbers(numbers);
            String formId = KingConstUtil.BD_Supplier;
            String resultJson = client.submit(formId, JSON.toJSONString ( submitBo ));
            Gson gson = new Gson();
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("供应商提交成功: {}", gson.toJson(repoRet.getResult()));
            } else {
                log.error("供应商提交失败: {}",gson.toJson(repoRet.getResult().getResponseStatus()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 金蝶供应商审核方法
     * @param docCode
     * @param client
     */
    public void audit(String docCode,K3CloudApi client){
        try{
            OrderAuditBo auditBo = new OrderAuditBo();
            List<String> numbers = new ArrayList<>();
            numbers.add(docCode);
            auditBo.setNumbers(numbers);
            String formId = KingConstUtil.BD_Supplier;
            String resultJson = client.audit(formId,JSON.toJSONString ( auditBo ));
            Gson gson = new Gson();
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("供应商审核成功:{}", gson.toJson(repoRet.getResult()));
            } else {
                log.error("供应商审核失败:{}",gson.toJson(repoRet.getResult().getResponseStatus()) );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 供应商推送金蝶对象
     * @param supplier
     * @return supplierBo
     */
    private SupplierBo assembleSupplier(SupplierEntity supplier){
        SupplierBo supplierBo = new SupplierBo();
        //创建组织 supplier.getCreateDept()
        BaseChildBo FCreateOrgId = new BaseChildBo().setFNumber(KingConstUtil.DEFAULT_ORG);
        supplierBo.setFCreateOrgId(FCreateOrgId);
        //编码
        supplierBo.setFNumber(supplier.getSupplierCode());
        //使用组织 supplier.getUseDept()
        BaseChildBo FUseOrgId = new BaseChildBo().setFNumber(KingConstUtil.DEFAULT_ORG);
        supplierBo.setFUseOrgId(FUseOrgId);
        //名称
        supplierBo.setFName(supplier.getSupplierName());
        //简称
        supplierBo.setFShortName(supplier.getForShort());
        //供应商分组
        BaseChildBo FGroup = new BaseChildBo().setFNumber(supplier.getSupplierGroup());
        supplierBo.setFGroup(FGroup);
        //对应组织 supplier.getCorrespondingOrganization()
//        BaseChildBo FCorrespondOrgId = new BaseChildBo().setFNumber(KingConstUtil.DEFAULT_ORG);
//        supplierBo.setFCorrespondOrgId(FCorrespondOrgId);
        //描述
        supplierBo.setFDescription(supplier.getDescInfo());
        //禁用人
        FConfirmerIdBo FForbiderId = new FConfirmerIdBo().setFUserID(supplier.getDisabledId());
        supplierBo.setFForbiderId(FForbiderId);
        //禁用日期
        if(Objects.nonNull(supplier.getDisabledDate())){
            supplierBo.setFForbidDate(dateFormat.format(supplier.getDisabledDate()));
        }
        //对应集团供应商
        BaseChildBo FGROUPSUPPLYID = new BaseChildBo().setFNumber(supplier.getGroupSupplier());
        supplierBo.setFGROUPSUPPLYID(FGROUPSUPPLYID);

        /***供应商基本信息***/
        FBaseInfoBo FBaseInfo = new FBaseInfoBo();
        //国家
        BaseChildBo FCountry = new BaseChildBo().setFNumber(supplier.getNationId());
        FBaseInfo.setFCountry(FCountry);
        //通讯地址
        FBaseInfo.setFAddress(supplier.getMailingAddress());
        //邮政编码
        FBaseInfo.setFZip(supplier.getZipCode());
        //语言
        BaseChildBo FLanguage = new BaseChildBo().setFNumber(supplier.getLanguage());
        FBaseInfo.setFLanguage(FLanguage);
        //公司网址
        FBaseInfo.setFWebSite(supplier.getCompanyWebsite());
        //行业
        BaseChildBo FTrade = new BaseChildBo().setFNumber(supplier.getIndustry());
        FBaseInfo.setFTrade(FTrade);
        //创立日期
        if(Objects.nonNull(supplier.getEstablishDate())){
            FBaseInfo.setFFoundDate(dateFormat.format(supplier.getEstablishDate()));
        }
        //法人代表
        FBaseInfo.setFLegalPerson(supplier.getLegalRepresentative());
        //注册资金(万元)
        if(StringUtils.isNotEmpty(supplier.getRegisteredCapital())){
            FBaseInfo.setFRegisterFund(Integer.parseInt(supplier.getRegisteredCapital()));
        }
        //工商登记号
        FBaseInfo.setFRegisterCode(supplier.getRegistrationNumber());
        //统一社会信用代码
        FBaseInfo.setFSOCIALCRECODE(supplier.getCreditCode());
        //生产经营许可证
        FBaseInfo.setFTendPermit(supplier.getProductionLicense());
        //注册地址
        FBaseInfo.setFRegisterAddress(supplier.getCompanyRegisteredAddress());
        //负责部门
        BaseChildBo FDeptId = new BaseChildBo().setFNumber(supplier.getChargeDept());
        FBaseInfo.setFDeptId(FDeptId);
        //负责人
        BaseChildBo FStaffId = new BaseChildBo().setFNumber(supplier.getChargePerson());
        FBaseInfo.setFStaffId(FStaffId);
        //供应商分类
        BaseChildBo FSupplierClassify = new BaseChildBo().setFNumber(supplier.getClassification());
        FBaseInfo.setFSupplierClassify(FSupplierClassify);
        //供应类别
        FBaseInfo.setFSupplyClassify(supplier.getSupplyCategory());
        //供应商等级
        BaseChildBo FSupplierGrade = new BaseChildBo().setFNumber(supplier.getSupplierLevel());
        FBaseInfo.setFSupplierGrade(FSupplierGrade);
        //公司类别
        BaseChildBo FCompanyClassify = new BaseChildBo().setFNumber(supplier.getCompanyCategory());
        FBaseInfo.setFCompanyClassify(FCompanyClassify);
        //公司性质
        BaseChildBo FCompanyNature = new BaseChildBo().setFNumber(supplier.getCompanyNature());
        FBaseInfo.setFCompanyNature(FCompanyNature);
        //公司规模
        BaseChildBo FCompanyScale = new BaseChildBo().setFNumber(supplier.getCompanySize());
        FBaseInfo.setFCompanyScale(FCompanyScale);
        supplierBo.setFBaseInfo(FBaseInfo);

        /***商务信息***/
        FBusinessInfoBo FBusinessInfo = new FBusinessInfoBo();
        //冻结人
        FConfirmerIdBo FFreezeOperator = new FConfirmerIdBo().setFUserID(supplier.getFreezingPerson());
        FBusinessInfo.setFFreezeOperator(FFreezeOperator);
        //冻结日期
        if(Objects.nonNull(supplier.getFreezeDate())){
            FBusinessInfo.setFFreezeDate(dateFormat.format(supplier.getFreezeDate()));
        }
        //采购组
        BaseChildBo FPurchaserGroupId = new BaseChildBo().setFNumber(supplier.getPurchaseGroup());
        FBusinessInfo.setFPurchaserGroupId(FPurchaserGroupId);
        //汇总公司
        BaseChildBo FParentSupplierId = new BaseChildBo().setFNumber(supplier.getSummaryCompany());
        FBusinessInfo.setFParentSupplierId(FParentSupplierId);
        //结算方式
        BaseChildBo FSettleTypeId = new BaseChildBo().setFNumber(supplier.getBalanceMethod());
        FBusinessInfo.setFSettleTypeId(FSettleTypeId);
        //默认价目表
        BaseChildBo FPRICELISTID = new BaseChildBo().setFNumber(supplier.getDefaultPriceList());
        FBusinessInfo.setFPRICELISTID(FPRICELISTID);
        //默认折扣表
        BaseChildBo FDiscountListId = new BaseChildBo().setFNumber(supplier.getDefaultDiscount());
        FBusinessInfo.setFDiscountListId(FDiscountListId);
        //供货方
        BaseChildBo FProviderId = new BaseChildBo().setFNumber(supplier.getSupply());
        FBusinessInfo.setFProviderId(FProviderId);
        //vmi
        FBusinessInfo.setFVmiBusiness(supplier.getIsVmi());
        //vmi仓库
        FBillTypeIDBo FVmiStockId = new FBillTypeIDBo().setFNUMBER(supplier.getVmiWarehouse());
        FBusinessInfo.setFVmiStockId(FVmiStockId);
        //启用供应商协同
        FBusinessInfo.setFEnableSL(supplier.getEnableCoordination());
        if(StringUtils.isNotEmpty(supplier.getEnsureRate())){
            //保证金比例
            FBusinessInfo.setFDepositRatio(Integer.parseInt(supplier.getEnsureRate()));
        }
        supplierBo.setFBusinessInfo(FBusinessInfo);

        /***财务信息***/
        FFinanceInfoBo FFinanceInfo = new FFinanceInfoBo();
        //对应客户
        BaseChildBo FCustomerId = new BaseChildBo().setFNumber(supplier.getCorrespondingCustomer());
        FFinanceInfo.setFCustomerId(FCustomerId);
        //结算币别
        BaseChildBo FPayCurrencyId = new BaseChildBo().setFNumber(supplier.getBalanceCurrency());
        FFinanceInfo.setFPayCurrencyId(FPayCurrencyId);
        //付款条件
        BaseChildBo FPayCondition = new BaseChildBo().setFNumber(supplier.getPaymentTerms());
        FFinanceInfo.setFPayCondition(FPayCondition);
        //结算方
        BaseChildBo FSettleId = new BaseChildBo().setFNumber(supplier.getBalanceParty());
        FFinanceInfo.setFSettleId(FSettleId);
        //单次预付额度
        if(StringUtils.isNotEmpty(supplier.getSinglePrepaymentLimit())){
            FFinanceInfo.setFPayAdvanceAmount(Integer.parseInt(supplier.getSinglePrepaymentLimit()));
        }
       //税分类
        BaseChildBo FTaxType = new BaseChildBo().setFNumber(supplier.getTaxType());
        FFinanceInfo.setFTaxType(FTaxType);
        //税务登记号
        FFinanceInfo.setFTaxRegisterCode(supplier.getTaxNumber());
        //收款方
        BaseChildBo FChargeId = new BaseChildBo().setFNumber(supplier.getPayee());
        FFinanceInfo.setFChargeId(FChargeId);
        //发票类型
        FFinanceInfo.setFInvoiceType(supplier.getInvoiceType());
        //默认税率
        FBillTypeIDBo FTaxRateId = new FBillTypeIDBo().setFNUMBER(supplier.getDefaultTax());
        FFinanceInfo.setFTaxRateId(FTaxRateId);
        //描述
        FFinanceInfo.setFFinanceDesc(supplier.getDescInfo());
        supplierBo.setFFinanceInfo(FFinanceInfo);

        /***银行信息***/
        if(!CollectionUtils.isEmpty(supplier.getBanks())){
            List<FBankInfoBo> FBankInfo = new ArrayList<>();
            List<BankEntity> bankList = supplier.getBanks();
            bankList.stream().filter(Objects::nonNull).forEach(bank -> {
                FBankInfoBo fBankInfoBo = new FBankInfoBo();
                //国家
                BaseChildBo FBankCountry = new BaseChildBo().setFNumber(bank.getOpeningCountry());
                fBankInfoBo.setFBankCountry(FBankCountry);
                //银行账号
                fBankInfoBo.setFBankCode(bank.getBankAccount());
                //账户名称
                fBankInfoBo.setFBankHolder(bank.getAccountName());
                //收款银行
                FBillTypeIDBo FBankTypeRec = new FBillTypeIDBo().setFNUMBER(bank.getDueBanke());
                fBankInfoBo.setFBankTypeRec(FBankTypeRec);
                //网点名称
                fBankInfoBo.setFTextBankDetail(bank.getBrancheName());
                //银行网点
                FBillTypeIDBo FBankDetail = new FBillTypeIDBo().setFNUMBER(bank.getBankBranches());
                fBankInfoBo.setFBankDetail(FBankDetail);
                //开户行地址
                fBankInfoBo.setFOpenAddressRec(bank.getOpenBankAddress());
                //开户银行
                fBankInfoBo.setFOpenBankName(bank.getBankName());
                //联行号
                fBankInfoBo.setFCNAPS(bank.getUnionPayAccount());
                //FSwiftCode
                fBankInfoBo.setFSwiftCode(bank.getSwiftCode());
                //币别
                BaseChildBo FBankCurrencyId = new BaseChildBo().setFNumber(bank.getCurrency());
                fBankInfoBo.setFBankCurrencyId(FBankCurrencyId);
                //是否默认
                if(StringUtils.isNotEmpty(bank.getIsDefault())){
                    fBankInfoBo.setFBankIsDefault(bank.getIsDefault().equals("1") ? true:false );
                }
                //描述
                fBankInfoBo.setFBankDesc(bank.getDescInfo());
                FBankInfo.add(fBankInfoBo);
            });
            supplierBo.setFBankInfo(FBankInfo);
        }

        /***组织信息***/
        System.out.println("组织信息："+supplier.getOrganizations());
        if(!CollectionUtils.isEmpty(supplier.getOrganizations())){
            List<FLocationInfoBo> FLocationInfo = new ArrayList<>();
            List<SupplierOrganizationEntity> organizationList = supplier.getOrganizations();
            organizationList.stream().filter(Objects::nonNull).forEach(supplierOrganization -> {
                FLocationInfoBo fLocationInfoBo = new FLocationInfoBo();
                //地点名称
                fLocationInfoBo.setFLocName(supplierOrganization.getLocationName());
                //联系人
                if(Objects.nonNull(supplierOrganization.getContractsId())){
                    IKingBaseContactsService kingBaseContactsService = SpringUtils.getBean(IKingBaseContactsService.class);
                    KingBaseContactsEntity kingBaseContactsEntity = kingBaseContactsService.getById(supplierOrganization.getContractsId());
                    if(Objects.nonNull(kingBaseContactsEntity)){
                        FBillTypeIDBo FLocNewContact = new FBillTypeIDBo().setFNUMBER(kingBaseContactsEntity.getContactsCode());
                        fLocationInfoBo.setFLocNewContact(new FBillTypeIDBo().setFNUMBER("001.001"));
                    }
                }
                //通讯地址
                fLocationInfoBo.setFLocAddress(supplierOrganization.getMailingAddress());
                //手机号
                fLocationInfoBo.setFLocMobile(supplierOrganization.getPhone());
                FLocationInfo.add(fLocationInfoBo);
            });
            supplierBo.setFLocationInfo(FLocationInfo);
        }

        /***联系人***/
        if(!CollectionUtils.isEmpty(supplier.getContracts())){
            List<FSupplierContactBo> FSupplierContact = new ArrayList<>();
            List<SupplierContactsEntity> supplierContracts = supplier.getContracts();
            supplierContracts.stream().filter(Objects::nonNull).forEach(supplierContract -> {
                FSupplierContactBo fSupplierContactBo = new FSupplierContactBo();
                fSupplierContactBo.setFContactId(supplierContract.getContactsCode());
                FSupplierContact.add(fSupplierContactBo);
            });
        }
        return supplierBo;
    }






}
